package cn.jiedanba.itext5.util;

import cn.jiedanba.itext5.bean.KeyWordBean;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.*;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.*;

public class KeyWordPDFUtil {
    // 定义返回页码
    private static int i = 0;
    private static com.itextpdf.awt.geom.Rectangle2D.Float boundingRectange =null;

    private static List<KeyWordBean> lists = null;
//	private static KeyWordBean bean = new KeyWordBean();

    //itext返回的坐标在字体的左下角

    public static Map<Integer, List<KeyWordBean>> getPDFText(String filePath) {
        Map<Integer, List<KeyWordBean>> map = new HashMap<Integer, List<KeyWordBean>>();
        try {
            PdfReader pdfReader = new PdfReader(filePath);
            int pageNum = pdfReader.getNumberOfPages();
            PdfReaderContentParser pdfReaderContentParser = new PdfReaderContentParser(pdfReader);

            for (i = 1; i <= pageNum; i++) {
                lists = new ArrayList<>();
                boundingRectange =new com.itextpdf.awt.geom.Rectangle2D.Float();
                pdfReaderContentParser.processContent(i, new RenderListener() {
                    @Override
                    public void renderText(TextRenderInfo textRenderInfo) {
                        Rectangle pageSize =  pdfReader.getPageSize(i);
                        String text = textRenderInfo.getText(); // 整页内容
                        if (text.length()>1){
                            String[] texts = text.split("");

                            for (int j=0;j<texts.length;j++) {
                                boundingRectange= textRenderInfo.getBaseline().getBoundingRectange();
                                Float  w =  boundingRectange.width;
                                Float  w2 = new Float(texts.length);
                                Float oneFontW = w/w2;
                                KeyWordBean bean = new KeyWordBean();
                                bean.setX(boundingRectange.x+(oneFontW*j));
                                bean.setY(boundingRectange.y);
                                bean.setPageWidth(pageSize.getWidth());
                                bean.setPageHeigh(pageSize.getHeight());
                                bean.setFontH(boundingRectange.getHeight());
                                bean.setFontW(boundingRectange.getWidth());
                                bean.setPage(i);
                                bean.setText(texts[j].trim());
                                lists.add(bean);
                            }
                        }else {
                            boundingRectange= textRenderInfo.getBaseline().getBoundingRectange();
                            KeyWordBean bean = new KeyWordBean();
                            bean.setX(boundingRectange.x);
                            bean.setY(boundingRectange.y);
                            bean.setPageWidth(pageSize.getWidth());
                            bean.setPageHeigh(pageSize.getHeight());
                            bean.setFontH(boundingRectange.getHeight());
                            bean.setFontW(boundingRectange.getWidth());
                            bean.setPage(i);
                            bean.setText(text);
                            lists.add(bean);
                        }

                    }
                    @Override
                    public void renderImage(ImageRenderInfo arg0) {
                        // TODO Auto-generated method stub
                    }
                    @Override
                    public void endTextBlock() {
                        // TODO Auto-generated method stub
                    }
                    @Override
                    public void beginTextBlock() {
                        // TODO Auto-generated method stub

                    }
                });
                map.put(i, lists);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }

    public static void main(String[] args) {
        Map<Integer, List<KeyWordBean>> keyWords = getPDFText("D:\\pdf\\src.pdf");
        System.out.println(keyWords.size());
    }


    //找院印
    public static List<KeyWordBean> getKeyWordByYY(Map<Integer, List<KeyWordBean>> map) {
        List<KeyWordBean> beanList = new ArrayList<>();

        KeyWordBean yearBean = null;
        KeyWordBean monthBean = null;
        KeyWordBean dayBean = null;


        String[] keyWords = {"[院印","【院印","(院印","（院印"};
        for (int j = 1;j<=map.size();j++){
            StringBuilder content = new StringBuilder();
            //每一页的内容
            List<KeyWordBean> list = map.get(j);
            //Collections.sort(list);//正序比较
            //遍历当前页
            KeyWordBean startBean = null;
            KeyWordBean bean = null;
            for(int i=0; i<list.size(); i++){
                //先将当前页的内容排列成行
                bean = list.get(i);
                String text = bean.getText();
                bean.setNum(i);
                if (startBean==null){
                    startBean = bean;
                }
                if(i+1 != list.size()){
                    content.append(text);
                    //判断当前行是否结束
                    KeyWordBean beanNext = list.get(i+1);
                    if(!(beanNext.getY()-bean.getY()<2&&beanNext.getY()-bean.getY()>-2)){
                        //判断当前行是否包含关键字
                        if(StringUtils.contains(content.toString(), keyWords[0])
                                ||StringUtils.contains(content.toString(), keyWords[1])
                                ||StringUtils.contains(content.toString(), keyWords[2])
                                ||StringUtils.contains(content.toString(), keyWords[3])){

                            //beanList.add(bean);
                            content.delete(0,content.length());
                            break;
                        }
                        bean = null;
                        startBean =null;
                        content.delete(0,content.length());
                    }
                }else {
                    //当前页最后一个字
                    content.append(text);
                    if(StringUtils.contains(content.toString(), keyWords[0])||StringUtils.contains(content.toString(), keyWords[1])){
                        content.delete(0,content.length());
                        break;
                    }
                    bean = null;
                    startBean =null;
                    content.delete(0,content.length());
                }
            }
            if(bean!=null){
                //找到院印两个字,然后向前和后找年月日
                //先向后5位找年

                int i = bean.getNum();
                if (i+11>=list.size()){
                yearBean = list.get(i+5);
                }
                StringBuilder contentNYR = new StringBuilder();
                if(yearBean!=null&&StringUtils.contains(yearBean.getText(),"年")){
                    startBean = list.get(i+1);
                    for(int c = i+6;c<=i+11;c++){
                        System.out.println((list.get(c-1).getY()-list.get(c).getY()<2&&list.get(c-1).getY()-list.get(c).getY()>-2));
                        if((list.get(c-1).getY()-list.get(c).getY()<2&&list.get(c-1).getY()-list.get(c).getY()>-2)){
                            contentNYR.append(list.get(c).getText());
                            //然后找月
                            if (contentNYR.length()<=3
                                    && StringUtils.contains(list.get(c).getText(),"月")){
                                monthBean = list.get(c);
                            }
                            //最后找日
                            if (monthBean!=null
                                    &&contentNYR.length()<=6
                                    && StringUtils.contains(list.get(c).getText(),"日")){
                                dayBean = list.get(c);
                                break;
                            }
                        }
                    }
                    contentNYR.delete(0,contentNYR.length());
                }else {
                    //如果没向后找到年就向前日
                    if(i-11>0){
                        dayBean = list.get(startBean.getNum()-1);
                        if(StringUtils.contains(dayBean.getText(),"日")){
                            for(int c = i-2;c>=i-11;c--){
                                //然后找月
                                if (contentNYR.length()<=3
                                        && StringUtils.contains(list.get(c).getText(),"月")){
                                    monthBean = list.get(c);
                                }
                                //最后找年
                                if (monthBean!=null
                                        &&contentNYR.length()<=6
                                        && StringUtils.contains(list.get(c).getText(),"年")){
                                    yearBean = list.get(c);
                                    startBean = list.get(c-4);
                                    break;
                                }
                            }
                        }
                    }
                    contentNYR.delete(0,contentNYR.length());
                }
                //处理坐标
                if(yearBean!=null&monthBean!=null&&dayBean!=null){
                    KeyWordBean returnBean = new KeyWordBean();
                    Float startX = startBean.getX();
                    Float endX = dayBean.getX();
                    Float a = startX+(endX-startX+dayBean.getFontW().floatValue())/2;
                    returnBean.setText("年");
                    returnBean.setX(a);
                    returnBean.setY(yearBean.getY());
                    returnBean.setPageWidth(yearBean.getPageWidth());
                    returnBean.setPageHeigh(yearBean.getPageHeigh());
                    returnBean.setPage(yearBean.getPage());
                    beanList.add(returnBean);

                }else{
                    int b = list.indexOf(bean);
                    beanList.add(list.get(b-2));
                    return beanList;

                }
            }
        }
        return beanList;
    }

    //ygsf上下盖章
    public static KeyWordBean getKeyWordByYGSF(String filePath) {
//        Map<Integer, List<KeyWordBean>> map = getPDFText("filePath");
        return null;
    }

    //找年月日中间点
    public static List<KeyWordBean> getKeyWordByNYR(Map<Integer, List<KeyWordBean>> map) {
        List<KeyWordBean> list2 = new ArrayList<>();
        KeyWordBean yearBean = null;
        KeyWordBean monthBean = null;
        KeyWordBean dayBean = null;
        KeyWordBean returnBean = new KeyWordBean();
        KeyWordBean startBean = null;
        for (int j = 1;j<=map.size();j++){
            StringBuilder content = new StringBuilder();
            List<KeyWordBean> list = map.get(j);
            //Collections.sort(list);//正序比较
            for(int i=0; i<list.size(); i++){

                KeyWordBean bean = list.get(i);
                String text = bean.getText();
                if (startBean==null){
                    startBean = bean;
                }
                if(i+1 != list.size()){
                    content.append(text);
                    KeyWordBean beanNext = list.get(i+1);
                    //判断是否为年
                    if (content.length()==5 && StringUtils.contains(text, "年")) {
                        yearBean = bean;
                        continue;
                    }
                    //判断月
                    if (StringUtils.contains(content.toString(), "年")
                            && content.length()<=8
                            && StringUtils.contains(text, "月")) {
                        monthBean = bean;
                        continue;
                    }
                    //判断日
                    if (StringUtils.contains(content.toString(), "年")
                            && StringUtils.contains(content.toString(), "月")
                            && content.length()<= 11
                            && StringUtils.contains(text, "日")) {
                        //是该行的最后一个字
                       if(beanNext.getY()!=bean.getY()){
                           dayBean = bean;
                           break;
                        }
                    }
                    if(beanNext.getY()!=bean.getY()){
                        startBean = null;
                        content.delete(0,content.length());
                        yearBean = null;
                        monthBean = null;
                    }
                }
            }
            //处理坐标
            if(yearBean!=null&monthBean!=null&&dayBean!=null){
                Float startX = startBean.getX();
                Float endX = dayBean.getX();
                Float a = startX+(endX-startX+dayBean.getFontW().floatValue())/2;


                returnBean.setX(a);
                returnBean.setY(yearBean.getY());
                returnBean.setPageWidth(yearBean.getPageWidth());
                returnBean.setPageHeigh(yearBean.getPageHeigh());
                returnBean.setPage(yearBean.getPage());

                list.add(returnBean);

            }
        }
        return list2;
    }

    public static KeyWordBean getKeyWordXY(Map<Integer, List<KeyWordBean>> map, int page, int num,String keyWord) {
        int keyMatch = 1;
        StringBuilder content = new StringBuilder();
        List<KeyWordBean> list = map.get(page);
        //Collections.sort(list);//正序比较
        StringBuilder builder = new StringBuilder();
        KeyWordBean returnBean = new KeyWordBean();
        for(int i=0; i<list.size(); i++){
            KeyWordBean bean = list.get(i);
            String text = bean.getText();
            if(i+1 != list.size()){
                KeyWordBean beanNext = list.get(i+1);
                    float x = beanNext.getX()-bean.getX();
                float y = beanNext.getY()-bean.getY();
                if(y == 0 && x <= 1){
//					System.out.print("去除因字体加粗产生的重复数字");
                }else{
                    System.out.println((!StringUtils.isEmpty(text) && keyWord.startsWith(text)) || content.length()>0);
                    if (StringUtils.contains(content.toString(), keyWord) || StringUtils.contains(text, keyWord)) {
                        if(keyMatch == num){
                            return bean;
                        }else{
                            keyMatch ++;
                        }
                        returnBean = bean;
                    }else if((!StringUtils.isEmpty(text) && keyWord.startsWith(text)) || content.length()>0){
                        content.append(text);
                        if(content.length() >= keyWord.length()){
                            if(StringUtils.contains(content.toString(), keyWord)){
                                if(keyMatch == num){
                                    return bean;
                                }else{
                                    keyMatch ++;
                                }
                                returnBean = bean;
                            }
                            content = new StringBuilder();
                        }
                    }
                }
            }else{
                if (StringUtils.contains(content.toString(), keyWord) || StringUtils.contains(text, keyWord)) {
                    if(keyMatch == num){
                        return bean;
                    }else{
                        keyMatch ++;
                    }
                    returnBean = bean;
                }else if((!StringUtils.isEmpty(text) && keyWord.startsWith(text)) || content.length()>0){
                    content.append(text);
                    if(content.length() >= keyWord.length()){
                        if(StringUtils.contains(content.toString(), keyWord)){
                            if(keyMatch == num){
                                return bean;
                            }else{
                                keyMatch ++;
                            }
                            returnBean = bean;
                        }
                        content = new StringBuilder();
                    }
                }
            }
        }
        return returnBean;
    }

    public static KeyWordBean getKeyWordBean(KeyWordBean bean, StringBuilder content, String keyWord, String text, int keyMatch, int num){
        if (StringUtils.contains(content.toString(), keyWord) || StringUtils.contains(text, keyWord)) {
            if(keyMatch == num){
                return bean;
            }else{
                keyMatch ++;
            }
        }else if((!StringUtils.isEmpty(text) && keyWord.startsWith(text)) || content.length()>0){
            content.append(text);
            if(content.length() >= keyWord.length()){
                if(StringUtils.contains(content.toString(), keyWord)){
                    if(keyMatch == num){
                        return bean;
                    }else{
                        keyMatch ++;
                    }
                }
                content = new StringBuilder();
            }
        }
        return null;

    }
}
